import java.util.concurrent.*;

/**
 * author: MaHX
 * date: 2019/9/23/21:48
 * description:
 * <p>
 * 线程池：提供一个线程队列，队列中保存所有等待状态的线程，避免了创建和销毁额外开销
 * <p>
 * 线程池体系结构：
 * java.utils.concurrent.Executor: 负责线程的使用与调度的根接口
 * |-- ExecutorService 子接口：线程池的主要接口
 * |-- ThreadPoolExecutor 线程池的实现类
 * |-- ScheduledExecutorService 子接口：负责线程的调度
 * |-- ScheduledThreadPoolExecutor 继承ThreadPoolExecutor.实现ScheduledExecutorService
 * <p>
 * <p>
 * 工具类： Executors
 * ExecutorService  newFixedThreadPool():创建固定大小的线程池
 * ExecutorService  newCacheThreadPool():缓存线程池，线程池数量不固定，可以根据需求自动更改数量
 * ExecutorService  newSingleThreadExecutor():创建单个线程池，线程池只有一个线程
 **/
public class TestThreadPool {
    public static void main(String args[]) throws Exception {
        ThreadPoolDemo threadPoolDemo = new ThreadPoolDemo();
//        new Thread(threadPoolDemo).start();
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
//            executorService.submit(threadPoolDemo);  用Runnable
               Future future = executorService.submit(new Callable<Integer>() {

                @Override
                public Integer call() throws Exception {
                    int sum = 0;
                    for (int j = 0; j <= 100; j++) {
                        sum += j;
                    }
                    return sum;
                }
            });
            System.out.println(Thread.currentThread().getName()+" : "+future.get());
        }
        executorService.shutdown();



    }

    static class ThreadPoolDemo implements Runnable {
        int sum = 0;

        @Override
        public void run() {
            for (int i = 0; i <= 100; i++) {
                sum += i;
            }
            System.out.println(Thread.currentThread().getName() + " : " + sum);
        }
    }
}
